package use;

import org.apache.log4j.Logger;

import java.nio.file.*;
import java.util.*;

public class FileUse {
    private Logger logger = Logger.getLogger(FileUse.class);
    private static FileUse manager;
    public static FileUse getManager() {
        if (manager == null) {
            manager = new FileUse();
        }
        return manager;
    }
    //更新文件存放目录规定有2个文件夹ftp文件夹下默认为自定义升级模式存放文件夹
    //ftp/upgrade 定义为设备默认请求升级文件存放文件夹
    private static String folder = "/home/ubuntu/ftp";

    //存储多个升级文件  文件名，文件内容
    private static Map<String,byte[]> file_map = new HashMap<>();

    public String[] read_file_name_all(){
        String[] v = new String[file_map.size()];
        file_map.keySet().toArray(v);
        return v;
    }
    public byte[] read_file_part(String file_name,int part){
        byte[] content = file_map.get(file_name);
        int length = 512;
        if (part * length > content.length){
            length = content.length % 512;
        }
        byte[] part_arr = new byte[length];
        System.arraycopy(content,part*length,part_arr,0,length);
        return part_arr;
    }
    public String read_file_name(){
        String file_name = null;
        try{
            Path path = Paths.get(folder + "/upgrade");
            if (!Files.exists(path)){
                logger.info("不存在默认文件夹:/upgrade");
            }
            file_name = Files.list(path).findFirst().get().getFileName().toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return file_name;
    }
    public int read_file_part_count(String file_name){
        return (int) Math.ceil(file_map.get(file_name).length / 512.0);
    }
    public void read_folder(){
        Path path = Paths.get(folder);
        List<String> file_list = new ArrayList<>();
        try{
            if (!Files.exists(path)){
                logger.info(String.format("创建文件夹:%s",folder));
                Files.createDirectories(path);
            }
            if (Files.list(path).count() > 0){
                Files.list(path).forEach(item -> {
                    try{
                        if (item.toString().contains(".bin")){
                            file_list.add(item.getFileName().toString());
                            if (!file_map.containsKey(item.getFileName().toString())){
                                logger.info(String.format("加载升级文件:%s",item.getFileName()));
                                file_map.put(item.getFileName().toString(),Files.readAllBytes(item));
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });
            }else if (file_map.size() > 0 && Files.list(path).count() == 0){
                logger.info("清空升级文件");
                file_map.clear();
            }
            if (file_list.size() > 0){
                Object[] keys = file_map.keySet().toArray();
                for (Object key : keys) {
                    if (!file_list.contains(key.toString())) {
                        logger.info(String.format("删除文件:%s",key));
                        file_map.remove(key.toString());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        FileUse.getManager().read_folder();
        System.out.println(Arrays.toString(FileUse.getManager().read_file_name_all()));
    }
    public void save_file(String directory,String file_name,byte[] content){
        try{
            Path path = Paths.get(folder+directory);
            if (!Files.exists(path)){
                logger.info(String.format("创建文件夹:%s",path.toString()));
                Files.createDirectories(path);
            }
            if(directory.equals("/upgrade")){
                Files.list(path).forEach(item ->{
                    try{
                        Files.delete(item.toAbsolutePath());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });
                logger.info(String.format("清空默认存放文件夹:%s",path.toString()));
            }
            path = Paths.get(folder+directory+"/"+file_name);
            if (Files.deleteIfExists(path)) {
                logger.info(String.format("删除已存在文件:%s",path.toString()));
            }
            Files.write(path,content);
            if(Files.exists(path)){
                logger.info(String.format("创建文件完成:%s",path.toString()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
